#!/usr/bin/env sh
# Generates a route based on the Mobility DB's spec'd bbox for two random
# points within the bbox. Sets arbitrarily high walk/transfer seconds params.
# Can be used as a coarse testing mechanism to make sure routing for a given
# source is feasible / working in the system.

rnd() {
  LOWER=$1
  UPPER=$2
  INTERVAL=$3

  INTERVALSIGN="$(awk 'BEGIN { print ('$LOWER' >= '$UPPER') ? "-" : "+" }')"
  seq $LOWER ${INTERVALSIGN}${INTERVAL} $UPPER | shuf | head -n1
}

genreq() {
  MDBID=$1
  FROMLAT=$2
  FROMLON=$3
  TOLAT=$4
  TOLON=$5
  echo '{
    filter: {mdbid: ['$MDBID']},
    from: {lat: '$FROMLAT', lon: '$FROMLON'},
    to: {lat: '$TOLAT', lon: '$TOLON'},
    max_walk_seconds: 9999999999,
    max_transfer_seconds: 999999
  }'
}

route() {
  MDBID="$1"

  echo "$MDBID" | grep '[0-9]+'
  BBOX="$(
    ./mobroute dbstatus -f '{mdbid: ['"$MDBID"']}' | jq '.[0].bbox' | grep -oE '[0-9,.-]+' | tr -d "\n"
  )"

  LATA="$(echo $BBOX | cut -d, -f1)"
  LONA="$(echo $BBOX | cut -d, -f2)"
  LATB="$(echo $BBOX | cut -d, -f3)"
  LONB="$(echo $BBOX | cut -d, -f4)"

  INTERVAL=0.01
  FROMLAT="$(rnd $LATA $LATB $INTERVAL)"
  FROMLON="$(rnd $LONA $LONB $INTERVAL)"

  TOLAT="$(rnd $LATA $LATB $INTERVAL)"
  TOLON="$(rnd $LONA $LONB $INTERVAL)"

  ./mobroute route -p "$(genreq $MDBID $FROMLAT $FROMLON $TOLAT $TOLON)"
}

if [ "$#" -eq 1 ]; then
  route $1
else
  echo "Pass first argument as MDBID"
fi
